package org.darkforest.common.services.impl;

import org.darkforest.common.logger.Logger;
import org.darkforest.common.services.GoodsService;
import org.darkforest.common.services.PMiaoShaService;
import org.darkforest.dao.mapper.PMiaoshaMapper;
import org.darkforest.enums.VariablePrefixEnum;
import org.darkforest.model.PMiaosha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Libing on 2015/6/25.
 */
@Service
public class PMiaoShaServiceImpl implements PMiaoShaService {

    @Autowired
    private PMiaoshaMapper pMiaoshaMapper;


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SimpleRedisServiceImpl redisService;


    public PMiaosha findMiaoShaByPage(PMiaosha pMiaosha) {

        pMiaosha.setResultList(pMiaoshaMapper.findPMiaoShaByCondition(pMiaosha));
        return pMiaosha;
    }

    /**
     * 新增秒杀活动
     *
     * @param pMiaosha
     */
    @Override
    public int addPMiaoSha(PMiaosha pMiaosha) {
        return pMiaoshaMapper.insertSelective(pMiaosha);
    }

    /**
     * 校验同一开始时间是否有相同的秒杀商品
     *
     * @param startTime
     * @param goodsId
     * @return
     */
    @Override
    public boolean checkMSAcitive(Integer startTime, Integer goodsId) {
        PMiaosha pMiaosha = new PMiaosha();
        pMiaosha.setGoodsId(goodsId);
        pMiaosha.setStartTime(startTime);
        List<PMiaosha> pMiaoshaList = this.pMiaoshaMapper.findPMiaoShaByCondition(pMiaosha);
        if(pMiaoshaList.size()>0)
            return false;
        else
            return true;
    }

    @Override
    public PMiaosha getNearestOne() {
        return pMiaoshaMapper.getNearestOne();
    }

    /**
     * 秒杀商品下单后在秒杀活动销售数量上+1
     * @param msId
     */
    public void updatePurchasedNum(Integer msId) {
//        Map<String,Object> map= new HashMap<String,Object>();
//        map.put("msId",msId);
//        map.put("goodsId",goodsId);
        this.pMiaoshaMapper.updatePurchasedNum(msId);
    }

    /**
     * 根据ID主键查询秒杀活动
     *
     * @param msId
     * @return
     */
    @Override
    public PMiaosha findMiaoshaById(Integer msId) {

        return pMiaoshaMapper.selectByPrimaryKey(msId);
    }

    /**
     * 修改秒杀活动  图片  商品除外
     * 同时在redis中添加修改标记位，便于前端进行刷新读取
     * @param pMiaosha
     */
    @Override
    public void updateSelectActive(PMiaosha pMiaosha) {
        this.pMiaoshaMapper.updateByPrimaryKeySelective(pMiaosha);
        String key = VariablePrefixEnum.MS_UPDATE_PRE.getKey_pre()+pMiaosha.getMsId();
        Logger.debug(PMiaoShaServiceImpl.class,"======update miaosh :"+key);
        redisService.setValue(key,"1");
    }

    @Override
    public PMiaosha getById(Integer msId) {
        return pMiaoshaMapper.selectByPrimaryKey(msId);
    }
}
